package com.pro.control;/*
    ClassName:LoginController
    Package:com.pro.control
    Description:
    @Date:2021/11/5 14:32
    @Author: 赵自强
*/

import com.pro.entity.JsonData;
import com.pro.entity.LoginRecord;
import com.pro.entity.User;
import com.pro.service.LoginService;
import com.pro.service.NavigationBarService;
import com.pro.utils.DateUtils;
import com.pro.utils.IPAndAddressUtils;
import com.pro.utils.MD5Util;
import com.pro.utils.VerificationCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserDetailsService userDetailsService;

    private List<Integer> jurisDiction;

    @Autowired
    private NavigationBarService service;

    @RequestMapping("/getJurisdiction")
    @ResponseBody
    public JsonData getJurisdiction(){
        return jurisDiction != null ? JsonData.buildSuccess(jurisDiction): JsonData.buildError("权限异常");
    }

    //judgeEnabled
    //判断账户是否启用
    @RequestMapping("/judgeEnabled")
    @ResponseBody
    public JsonData judgeEnabled(String account){
        User user = loginService.judgeEnabled(account);


        JsonData jsonData = new JsonData();
        return user!=null?jsonData.buildSuccess(user):jsonData.buildError("后台数据错误");
    }

    @RequestMapping(value = "/getLogin")
    @ResponseBody
    public JsonData login(String account,String password, HttpSession session){
        User login = loginService.login(account, password);
        /*session.setAttribute("user",login);*/
        JsonData jsonData = new JsonData();
        return login!=null?jsonData.buildSuccess(login):jsonData.buildError("后台数据错误");
    }

    @RequestMapping("/login")
    public String getUser(HttpSession session){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        UserDetails userDetails = userDetailsService.loadUserByUsername(name);
        User login = loginService.login(name, userDetails.getPassword());
        jurisDiction  = service.getDeptAndUser(login.getUserId());
        System.err.println(jurisDiction);
        if(session.getAttribute("user") == null){
            System.err.println("bb");
            Map<String, Object> map = IPAndAddressUtils.getIPAndAddressUtils();
            LoginRecord loginRecord = new LoginRecord(null,login.getUserId(),map.get("ip").toString(),
                    map.get("addr").toString(),2, DateUtils.transDate(new Date()),2);
            addLoginRecord(loginRecord);
        }
        if(login != null){
            session.setAttribute("user",login);
        }
        return "index";
    }

    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            VerificationCodeUtils randomValidateCode = new VerificationCodeUtils();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //验证
    @RequestMapping(value = "/verificationcode")
    @ResponseBody
    public JsonData verification(HttpSession session,String code){
        String random = null;
        try {
            //从session中获取随机数
            random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
            if (random == null) {
                return random != null ? JsonData.buildSuccess(false) : JsonData.buildError("服务端错误");
            }
            if (random.equals(code.toUpperCase())) {
                return random != null ? JsonData.buildSuccess(true) : JsonData.buildError("服务端错误");
            } else {
                return random != null ? JsonData.buildSuccess(false) : JsonData.buildError("服务端错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return random != null ? JsonData.buildSuccess(false) : JsonData.buildError("服务端错误");
    }

    @RequestMapping(value = "/verification")
    private JsonData addLoginRecord(LoginRecord loginRecord){
        Boolean aBoolean = loginService.addLoginRecord(loginRecord);
        JsonData jsonData = new JsonData();
        return aBoolean?jsonData.buildSuccess(aBoolean):jsonData.buildError("后台数据错误");
    }

    /**
     * @ClassName JsCarousel
     * @Author 谭金诚
     * @Date 2021/11/10
     */
    @RequestMapping("/loginOut")
    @ResponseBody
    public JsonData doGet(HttpSession session, HttpServletResponse response) {
        // 删除session的指定属性
        session.removeAttribute("user");
        session.invalidate();
        boolean b = true;
        return b != false ? JsonData.buildSuccess(b) : JsonData.buildError("服务端错误");
    }

    //
    @RequestMapping("/logOut")
    public String logOut(){
        return "index";
    }

}
